;
(function (call) {
    var main = {
        userInfo: null,
        qbTime: '',
        qxyb06: false,
        areaData: [],
        lon: [],
        lat: [],
        curClass: '',
        windName: { '北风': "N", '东北风': "NE", '东风': "E", '东南风': "SE", '南风': "S", '西南风': "SW", '西风': "W", '西北风': "NW", },
        init: function () {
            this.initView();
            this.bindEvt();
        },
        initView: function () {
            var userInfo = $("#userInfo").data('info');
            this.userInfo = userInfo;
            $(".rainfall .head label").text(userInfo.smuser.name);
            var productInfo = $(".task-menu-list li.active").data('product');
            var qbTime = new Date().format('yyyy年MM月dd日');
            $("#publishTime").val(qbTime);
            if (productInfo.fortime == '05:30') {
                this.qxyb06 = true;
                $(".list-right a").text('05时');
            } else {
                $(".list-right a").text('16时');
            }
            this.getAreaData();
        },
        getAreaData: function () {
            var that = this;
            $.getJSON(api.internal.sxsyb.queryHourYbStation, { stationType: '1' }, function (res) {
                if (!res.isSuccess || !res.data) return;
                var lon = [], lat = [];
                var arr = res.data
                var arrList = arr.filter(ele => ele.stationId !== "54622" && ele.stationId !== "54527" && ele.stationId !== "54528" && ele.stationId !== "54526");
                for (var i = 0; i < arrList.length; i++) {
                    lon.push(arrList[i].lon);
                    lat.push(arrList[i].lat);
                }
                that.areaData = arrList;
                that.lon = lon;
                that.lat = lat;
                that.getQxybDataDetail(arrList, lon, lat);
            })
        },
        getParams: function () {
            var fcstTime = new Date().format('yyyyMMdd080000');
            if (!this.qxyb06) {
                fcstTime = new Date().format('yyyyMMdd200000');
            }
            var params = {
                fcstTime: fcstTime,
                element: 'TP,TMAX,TMIN,EDA,WEA',
                startPeriod: 0,
                endPeriod: 24,
                interval: 12,
                stationType: 0,
            }
            return params;
        },
        initQxybData: function (areaData, lon, lat) {
            var that = this;
            var $body = $(".rainfall_table tbody").empty();
            var params = that.getParams();
            params.lat = lat.join(',');
            params.lon = lon.join(',');
            var url = api.external.getGdybDataByParamData
            loading.add('.cafe-container');
            $.ajax({
                type: "get",
                url: url,
                dataType: 'json',
                contentType: "application/json;charset=utf-8",
                data: params
            }).done(function (res) {
                loading.remove();
                if (!res.success || !res.resultData) return;
                var resultData = res.resultData
                for (var i = 0; i < areaData.length; i++) {
                    var dataObj = areaData[i];
                    var msg = areaData[i].lon + '_' + areaData[i].lat
                    var tmin = resultData[msg]['TMIN'][0][1] == '9999' ? '--' : resultData[msg]['TMIN'][0][1]
                    var tmax = resultData[msg]['TMAX'][0][1] == '9999' ? '--' : resultData[msg]['TMAX'][0][1]
                    var wd = resultData[msg]['EDA'][2][0].split('_');
                    var wp = resultData[msg]['EDA'][3][0].split('_');
                    var wd1 = resultData[msg]['EDA'][2][1].split('_');
                    var wp1 = resultData[msg]['EDA'][3][1].split('_');
                    var wdLi = that.windName[wd[0]],
                        wpLi = wpLi = wp[0],
                        wdLi1 = that.windName[wd1[0]],
                        wpLi1 = wp1[0];
                    if (wd.length > 1 && wd[0] != wd[1]) {
                        wdLi = that.windName[wd[0]] + WindUtil.getWindConcat(resultData[msg]['EDA'][2][0]) + that.windName[wd[1]]
                    }
                    if (wp.length > 1 && wp[0] != wp[1]) {
                        wpLi = wp[0] + '转' + wp[1]
                    }
                    if (wd1.length > 1 && wd1[0] != wd1[1]) {
                        wdLi1 = that.windName[wd1[0]] + WindUtil.getWindConcat(resultData[msg]['EDA'][2][1]) + that.windName[wd1[1]]
                    }
                    if (wp1.length > 1 && wp1[0] != wp1[1]) {
                        wpLi1 = wp1[0] + '转' + wp1[1]
                    }
                    var stationName = dataObj.stationName
                    if (stationName == '天津市') {
                        stationName = '市区及新四区'
                    }
                    var tr = '<tr><td>' + stationName + '<input type="hidden" class="stationName" value="' + stationName + '"></td>'
                    if (that.qxyb06) {
                        tr += '<td><span class="todayDay">今天白天</span><input type="hidden" class="todayDay" value="今天白天">'
                        tr += '<span class="tonight">今天夜间</span><input type="hidden" class="tonight" value="今天夜间"></td>'
                    } else {
                        tr += '<td><span class="tonight">今天夜间</span><input type="hidden" class="tonight" value="今天夜间">'
                        tr += '<span class="todayDay">明天白天</span><input type="hidden" class="todayDay" value="明天白天"></td>'
                    }
                    tr += '<td><input type="text" class="wea" value="' + resultData[msg]['WEA'][0][0] + '">'
                    tr += '<input type="text" class="wea2" value="' + resultData[msg]['WEA'][0][1] + '"></td>'
                    tr += '<td><input type="text" class="rainchance" value="' + weatherUtil.getVal(resultData[msg]['WEA'][0][0]) + '">'
                    tr += '<input type="text" class="rainchance2" value="' + weatherUtil.getVal(resultData[msg]['WEA'][0][1]) + '"></td>'
                    tr += '<td><input type="text" value="' + wdLi + wpLi + '" class="wd1">'
                    tr += '<input type="text" value="' + wdLi1 + wpLi1 + '" class="wd2"></td>'
                    if (that.qxyb06) {
                        tr += '<td><div><a>最高</a><input type="text" value="' + tmax + '" class="tmax"></div>'
                        tr += '<div><a>最低</a><input type="text" value="' + tmin + '" class="tmin"></div></td></tr>'
                    } else {
                        tr += '<td><div><a>最低</a><input type="text" value="' + tmin + '" class="tmin"></div>'
                        tr += '<div><a>最高</a><input type="text" value="' + tmax + '" class="tmax"></div></td></tr>'
                    }
                    var $tr = $(tr)
                    $body.append($tr);
                }
                if (that.qxyb06) {
                    var $tr2 = $(`<tr class="display:none"></tr>`);
                    $body.append($tr2);
                    return;
                }
                params.startPeriod = params.endPeriod;
                params.endPeriod = params.endPeriod + 24
                params.interval = 24;
                params.lon = 117.21;
                params.lat = 39.07;
                $.ajax({
                    type: "get",
                    url: url,
                    dataType: 'json',
                    contentType: "application/json;charset=utf-8",
                    data: params
                }).done(function (res2) {
                    if (!res2.success || !res2.resultData) return;
                    var resultData2 = res2.resultData;
                    var time = new Date();
                    time.setDate(time.getDate() + 2);
                    time = time.format("yyyy年MM月dd日");
                    var wea = resultData2['117.21_39.07']['WEA'][0];
                    var $tr2 = $(`<tr>
                <td>趋势<input type="hidden" class="qs" value="趋势"></td>
                <td><span style="border:none;line-height: 35px;">明天夜间到${time}</span>
                <input type="hidden" class="qstime" value="明天夜间到${time}"></td>
                <td colspan="4"><input type="text" class="qswea" style="border:none;" value="${wea}"></td></tr>
                `);
                    $body.append($tr2);
                });
            });
        },
        publishProQxYb: function () {
            var that = this;
            var productInfo = $(".task-menu-list li.active").data('product');
            var dataVal = [];
            $(".rainfall_table tbody tr").each(function (i, tr) {
                var list = [];
                var stationName = $(tr).find('.stationName').val()
                var todayDay = $(tr).find('.todayDay').text()
                var wea = $(tr).find('.wea').val()
                var rainchance = $(tr).find('.rainchance').val()
                var wd1 = $(tr).find('.wd1').val()
                var tmax = $(tr).find('.tmax').val()
                tmax = "最高 " + tmax
                var tonight = $(tr).find('.tonight').text()
                var wea2 = $(tr).find('.wea2').val()
                var rainchance2 = $(tr).find('.rainchance2').val()
                var wd2 = $(tr).find('.wd2').val()
                var tmin = $(tr).find('.tmin').val()
                tmin = "最低 " + tmin
                if (that.qxyb06) {
                    if (i == 7) {
                        list.push('1,1,1,1,1,1,1,1,1,1,1');
                    } else {
                        list.push(stationName + ',' + todayDay + ',' + wea + ',' + rainchance + ',' + wd1 + ',' +
                            tmax + ',' + tonight + ',' + wea2 + ',' + rainchance2 + ',' + wd2 + ',' + tmin);
                    }
                } else {
                    if (i == 7) {
                        var qs = $(".qs").val(),
                            qsTime = $(".qstime").val(),
                            qswea = $(".qswea").val();
                        list.push(qs + ',' + qsTime + ',' + qswea + ',1,1,1,1,1,1,1,1');
                    } else {
                        list.push(stationName + ',' + tonight + ',' + wea + ',' + rainchance + ',' + wd1 + ',' +
                            tmin + ',' + todayDay + ',' + wea2 + ',' + rainchance2 + ',' + wd2 + ',' + tmax);
                    }
                }
                list = list[0].split(',')
                dataVal.push(list)
            })
            dataVal = JSON.stringify(dataVal);
            var tempData = {
                "tempData": {
                    "curTagData": {
                        "z_qxyb01_02": {
                            "val": dataVal
                        },
                        "i_qxyb01_date01": {
                            "val": $("#publishTime").val()
                        }
                    }
                }
            }
            if (!that.qxyb06) {
                tempData = {
                    "tempData": {
                        "curTagData": {
                            "z_qxyb02_02": {
                                "val": dataVal
                            },
                            "i_qxyb02_date01": {
                                "val": $("#publishTime").val()
                            }
                        }
                    }
                }
            }
            tempData = JSON.stringify(tempData)
            var params = {
                product_id: productInfo.productId,
                fortime: productInfo.fortime,
                forecasterId: that.userInfo.smuser.iid,
                jsonStr: tempData,
				taskId:productInfo.taskId
            }
            $.post(api.internal.qxyb.publishProQxYb, params, function (res) {
                if (res.isSuccess) {
                    alert("发布成功");
                    CafeJS.menuFunc.setTask();
                    that.getQxybDataDetail(that.areaData, that.lon, that.lat);
                } else {
                    alert("发布失败");
                }
            })
        },
        // 获取区县预报数据
        getQxybDataDetail: function (areaData, lon, lat) {
            var that = this;
            var productInfo = $(".task-menu-list li.active").data('product');
            var time = new Date().format('yyyy-MM-dd 08:00:00')
            if (!that.qxyb06) {
                time = new Date().format('yyyy-MM-dd 20:00:00');
            }
            var params = {
                product_id: productInfo.productId,
                fortime: productInfo.fortime,
                queryTime: time
            }
            $.getJSON(api.internal.common.getProductDetail, params, function (res) {
                if (!res.isSuccess) return;
                if (JSON.stringify(res.data) == "{}") {
                    that.initQxybData(areaData, lon, lat);
                } else {
                    that.getQxybData(res.data);
                }
            })
        },
        getQxybData: function (data) {
            var item = JSON.parse(data.data.content);
            item = item.tempData.curTagData;
            var publishTime = '';
            var tableData = '';
            if (this.qxyb06) {
                publishTime = item.i_qxyb01_date01.val
                tableData = JSON.parse(item.z_qxyb01_02.val)
            } else {
                publishTime = item.i_qxyb02_date01.val;
                tableData = JSON.parse(item.z_qxyb02_02.val);
            }
            $("#publishTime").val(publishTime);
            this.buildQxybTable(tableData)
        },
        buildQxybTable: function (tableData) {
            var that = this;
            var $body = $(".rainfall_table tbody").empty();
            for (var i = 0; i < tableData.length; i++) {
                var tr = "";
                if (i != 7) {
                    tr = '<tr><td>' + tableData[i][0] + '<input type="hidden" class="stationName" value="' + tableData[i][0] + '"></td>'
                    if (that.qxyb06) {
                        tr += '<td><span class="todayDay">今天白天</span><input type="hidden" class="todayDay" value="今天白天">'
                        tr += '<span class="tonight">今天夜间</span><input type="hidden" class="tonight" value="今天夜间"></td>'
                    } else {
                        tr += '<td><span class="tonight">今天夜间</span><input type="hidden" class="tonight" value="今天夜间">'
                        tr += '<span class="todayDay">明天白天</span><input type="hidden" class="todayDay" value="明天白天"></td>'
                    }
                    tr += '<td><input type="text" class="wea" value="' + tableData[i][2] + '">'
                    tr += '<input type="text" class="wea2" value="' + tableData[i][7] + '"></td>'
                    tr += '<td><input type="text" class="rainchance" value="' + tableData[i][3] + '">'
                    tr += '<input type="text" class="rainchance2" value="' + tableData[i][8] + '"></td>'
                    tr += '<td><input type="text" value="' + tableData[i][4] + '" class="wd1">'
                    tr += '<input type="text" value="' + tableData[i][9] + '" class="wd2"></td>'
                    if (that.qxyb06) {
                        tr += '<td><div><a>最高</a><input type="text" value="' + tableData[i][5].split(' ')[1] + '" class="tmax"></div>'
                        tr += '<div><a>最低</a><input type="text" value="' + tableData[i][10].split(' ')[1] + '" class="tmin"></div></td></tr>'
                    } else {
                        tr += '<td><div><a>最低</a><input type="text" value="' + tableData[i][5].split(' ')[1] + '" class="tmin"></div>'
                        tr += '<div><a>最高</a><input type="text" value="' + tableData[i][10].split(' ')[1] + '" class="tmax"></div></td></tr>'
                    }
                } else {
                    if (that.qxyb06) {
                        tr += '<tr class="display:none"></tr>';
                    } else {
                        tr += '<tr><td>趋势<input type="hidden" class="qs" value="趋势"></td>'
                        tr += '<td><span style="border:none;line-height: 35px;">' + tableData[i][1] + '</span>'
                        tr += '<input type="hidden" class="qstime" value="' + tableData[i][1] + '"></td>'
                        tr += '<td colspan="4"><input type="text" class="qswea" style="border:none;" value="' + tableData[i][2] + '"></td></tr>'
                    }
                }
                var $tr = $(tr)
                $body.append($tr);
            }
        },
        // 批量编辑弹框
        editPop: function (curClass, offset) {
            $(".edit_pop").remove();
            var L = offset.left + 42;
            if (curClass == 'tmax' || curClass == 'tmin') {
                L = offset.left - 425
            }
            if (curClass == 'rainchance' || curClass == 'rainchance2' || curClass == 'tmax' || curClass == 'tmin') {
                var $div = $('<div>').addClass('edit_pop').css({
                    left: L,
                    top: offset.top
                });
                var list = '<div class="edit_pop_head"><i class="edit_close">×</i></div>'
                list += '<div class="edit_pop_body"><input type="number" value="1" class="edit_input1">'
                list += '<div class="oper_div"><span class="jia">+</span><span class="jian">-</span><span class="equal">=</span></div></div>'
                var $list = $(list);
                $(".rainfall").append($div.append($list));
            }
        },
        bindEvt: function () {
            var that = this;
            $(".remake_opr").click(function () {
                that.initQxybData(that.areaData, that.lon, that.lat);
            })
            $(".publish_opr").click(function () {
                that.publishProQxYb();
            })
            $(".rainfall_table tbody").on('change', '.wea', function () {
                var val = $(this).val();
                $(this).parent().siblings().find('.rainchance').val(weatherUtil.getVal(val));
            }).on('change', '.wea2', function () {
                var val = $(this).val();
                $(this).parent().siblings().find('.rainchance2').val(weatherUtil.getVal(val));
            }).bind('contextmenu', function () {
                return false;
            }).on('mousedown', 'input', function (e) {
                $(".edit_pop").remove();
                var curClass = $(this).attr('class').split(' ')[0], offset = $(this).offset(),
                    curClass2 = $(this).parent().siblings().find('input').attr('class').split(' ')[0];
                that.curClass = curClass;
                if (e.which == 3) {
                    if (curClass == 'tmax' || curClass == 'tmin') {
                        $(this).closest('.rainfall_table').find('input').removeClass('active');
                        $(this).addClass('active').closest('.rainfall_table').find('.' + curClass).addClass('active');
                        $(this).closest('.rainfall_table').find('.' + curClass2).removeClass('active');
                    } else {
                        $(this).closest('div').find('input').removeClass('active');
                        $(this).addClass('active').closest('div').find('.' + curClass).addClass('active');
                        $(this).closest('div').find('.' + curClass2).removeClass('active');
                    }
                    that.editPop(curClass, offset);
                } else {
                    if (curClass == 'tmax' || curClass == 'tmin') {
                        $(this).closest('.rainfall_table').find('input').removeClass('active');
                    } else {
                        $(this).closest('div').find('input').removeClass('active');
                    }
                }
            }).on('change', 'input', function (e) {
                var curClass = $(this).attr('class').split(' ')[0], val = $(this).val();
                if (curClass == 'wd1' || curClass == 'wd2' || curClass == 'wea' || curClass == 'wea2') {
                    $(this).closest('tr').siblings().find('.active').val(val);
                }
                if (curClass == 'wea') {
                    $('.active').parent().siblings().find('.rainchance').val(weatherUtil.getVal(val));
                }
                if (curClass == 'wea2') {
                    $('.active').parent().siblings().find('.rainchance2').val(weatherUtil.getVal(val));
                }
            }).on('blur', 'input', function (e) {
                var curClass = $(this).attr('class').split(' ')[0];
                if (curClass == 'rainchance' || curClass == 'rainchance2' || curClass == 'tmax' || curClass == 'tmin') return;
                $(this).removeClass('active').closest('tr').siblings().find('.' + curClass).removeClass('active');
            })
            $(".rainfall").on('click', '.edit_close', function () {
                $(".edit_pop").remove();
                $(".rainfall_table").find('input').removeClass('active');
            }).on('click', '.jia', function () {
                var val1 = $('.edit_input1').val();
                if (that.curClass == 'rainchance' || that.curClass == 'rainchance2') {
                    $(".rainfall_table tr").find('input.active').each(function (i, item) {
                        var itemVal = Number($(item).val().replace('%', '')) + Number(val1)
                        $(item).val(itemVal + '%')
                    })
                } else {
                    $(".rainfall_table tr").find('input.active').each(function (i, item) {
                        var itemVal = Number($(item).val()) + Number(val1)
                        $(item).val(itemVal)
                    })
                }
            }).on('click', '.jian', function () {
                var val1 = $('.edit_input1').val();
                if (that.curClass == 'rainchance' || that.curClass == 'rainchance2') {
                    $(".rainfall_table tr").find('input.active').each(function (i, item) {
                        var itemVal = Number($(item).val().replace('%', '')) - Number(val1)
                        $(item).val(itemVal + '%')
                    })
                } else {
                    $(".rainfall_table tr").find('input.active').each(function (i, item) {
                        var itemVal = Number($(item).val()) - Number(val1)
                        $(item).val(itemVal)
                    })
                }
            }).on('click', '.equal', function () {
                var val1 = $('.edit_input1').val();
                if (that.curClass == 'rainchance' || that.curClass == 'rainchance2') {
                    $(".rainfall_table").find('.active').val(val1 + '%');
                } else {
                    $(".rainfall_table").find('.active').val(val1);
                }
            })
        },
    };
    if (typeof call === 'function') {
        call(main);
    }
})(function (main) {
    main.init();
})